<?php
// +----------------------------------------------------------------------
// | API中间件
// +----------------------------------------------------------------------

namespace app\middleware;

use think\facade\Request;
use think\Response;

class ApiMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 设置跨域头
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        
        // 处理OPTIONS预检请求
        if (Request::method() === 'OPTIONS') {
            return Response::create('', 200);
        }

        // 设置响应头
        $response = $next($request);
        
        if ($response instanceof Response) {
            $response->header([
                'Content-Type' => 'application/json; charset=utf-8',
                'Cache-Control' => 'no-cache, no-store, must-revalidate',
                'Pragma' => 'no-cache',
                'Expires' => '0'
            ]);
        }

        return $response;
    }
}